package lv.dysnomia.songs.server.wiki

import scala.xml.Unparsed
import scala.xml.MetaData
import scala.xml.TopScope
import scala.xml.Elem
import scala.collection.mutable.LinkedList
import scala.xml.{ Node, NodeSeq, Text }

object WikiProc {
  val unparsedBR = Unparsed("<br/>")

  def eval(arg: WikiExpr): NodeSeq = arg match {
    case PcData(s) => new Text(s)
    case Em(e) => <em>{ eval(e) }</em>
    case Strong(e) => <strong>{ eval(e) }</strong>
    case BreakLine() => unparsedBR
//    case BreakLine() => <br/>
    case Sequence(exprs: List[WikiExpr]) => concat(exprs.map(eval), "")
  }

  def eval(arg: WikiBlock): NodeSeq = arg match {
    case PBlock(e: WikiExpr) => <p>{ eval(e) }</p>
    case OlBlock(items: List[WikiExpr]) => <ol>{
      concatItems(items.map(eval))
    }</ol>
    case UlBlock(items: List[WikiExpr]) => <ul>{
      concatItems(items.map(eval))
    }</ul>
  }

  def eval(args: List[WikiBlock]): NodeSeq = concat(args.map(eval), "\n")

  def main(args: Array[String]): Unit = {
    println(eval(Em(Strong(PcData("abc")))))
    println(eval(Sequence(List(Em(PcData("aa")), BreakLine(), PcData(" bb")))))
//    println(<ol>{ concatItems(List(new Text("aaa"), <span>bbbb</span>)) }</ol>)
//
//    var lastPar = Nil.asInstanceOf[List[String]]
//    lastPar = "aa" :: lastPar
//    lastPar = "bbb" :: lastPar
//    for (l <- lastPar) { println("item is " + l) }
  }

  def concat(exprs: List[NodeSeq], sep: String): NodeSeq = exprs match {
    case Nil => new Text("")
    case item :: tail => item ++ (new Text(sep)) ++ concat(tail, sep)
  }

  def concatItems(items: List[NodeSeq]): NodeSeq = items match {
    case Nil => new Text("")
    case item :: tail => <li>{ item }</li> ++ (new Text("\n")) ++ concatItems(tail)
  }

}